package com.bgdCA.auth.interceptor;

import com.bgdCA.auth.entity.TokenInfo;
import com.bgdCA.auth.exception.BiccException;
import com.bgdCA.auth.exception.BiccExceptionEnum;
import com.bgdCA.auth.properties.JwtProperties;
import com.bgdCA.auth.utils.CookieUtils;
import com.bgdCA.auth.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName cookiesInterceptor
 * @Description TODO
 * @Author AlvinZheng
 * @Date 2020/7/31 23:19
 * @Version 1.0
 **/
@Order(2)
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        log.info("调用TokenInterceptor拦截器");

        TokenInfo tokenInfo;
        System.out.println(request.getRequestURL().toString());
        //得到对应cookies，没有就返回，有就进行验证
        String token = CookieUtils.getCookieValue(request, "token", true);

        if (token == null) {
            log.info("Not find token in cookies.");
            throw new BiccException(BiccExceptionEnum.COOKIES_NOT_FOUND);
        }
        try {
            log.info("查询cookies " + token);
            tokenInfo = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
            System.out.println(tokenInfo.toString());
        } catch (Exception e) {
            e.printStackTrace();
            log.info("查询失败");
            return false;
        }
        //   System.out.println("111222333444555666777");
        if (tokenInfo != null) {
            log.info("查询成功" + tokenInfo.toString());
            request.setAttribute("tokenInfo", tokenInfo);
            return true;
        }
        return false;
    }


}
